/*
 * Application : Deploy Depot
 * Page : common.js
 * Purpose: 
 * Created Date : Jan 03, 2012
 * 
 */ 
		
var common = new function() {
	
	var defaultDateFormat = 'mm/dd/yy';
	
	/**
	 * Alert box to show message
	 */
	this.showMessage = function(divMessageContainerId, message, successflag){
		document.getElementById(divMessageContainerId).innerHTML = message;
		if(commonValidation.NullValidate(successflag) && (successflag == true)){
			document.getElementById(divMessageContainerId).style.color = '#5EBB01';
		}else {
			document.getElementById(divMessageContainerId).style.color = '#FB003F';
				 	 
		}
			
		//alert(message);
	};
	/**
	 * Asynchronous ajax Call.
	 */
	this.executeAJAX = function(urlpath, methodVal, formData , callBackFunName) {
		
		try{
			var xmlHttpRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
			
			if (!commonValidation.NullValidate(xmlHttpRequest)) { return; }
			xmlHttpRequest.open(methodVal, urlpath, true);	
			xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			xmlHttpRequest.onreadystatechange = callBackFunName;
			xmlHttpRequest.send(formData);
		
		} catch(e) {
			common.showMessage("divMessage","Unable to process client request!! Please contact application admin");
		}		
	};
	
	/**
	 * Proxy jquery ajax call(Synchronous). Disabling Asynchronous feature.
	 */
	(function($) {
		  // jQuery on an empty object, we are going to use this as our Queue
		  var ajaxQueue = $({});

		  $.ajaxQueue = function(ajaxOpts) {
		    // hold the original complete function
		    var oldComplete = ajaxOpts.complete;

		    // queue our ajax request
		    ajaxQueue.queue(function(next) {

		      // create a complete callback to fire the next event in the queue
		      ajaxOpts.complete = function() {
		        // fire the original complete if it was there
		        if (oldComplete) oldComplete.apply(this, arguments);

		        next(); // run the next query in the queue
		      };

		      // run the query
		      $.ajaxFileUpload(ajaxOpts);
		    });
		  };

		})(jQuery);
	
	/**
	 * Asynchronous jquery ajax call for file upload.
	 */
	this.executeFileUpload = function(urlpath, fileId, callBackFunName) {
		
		$.ajaxQueue({
			url : urlpath,
			secureuri : false,
			fileElementId : fileId,
			dataType : "xml",
			success : callBackFunName,
			error : function(e){
				alert("Error:"+e.message);
				}
		});
	};
	
	/**
	 * read CDATA value from XML node.
	 */
	this.getCDATAValue = function (node) {
		if (node.hasChildNodes()) { 
			var node2=node.firstChild;
			while ((node2) && (node2.nodeType!=4))
				node2=node2.nextSibling;
			if ((node2) && (node2.nodeType==4))
				return node2.textContent; //encounter CDATA
		};
		return null;
	}; 
	
	/**
	 * check status for callback StateChangeForXML
	 */
	this.checkStateChange = function(obj){
		if(obj.readyState == 4 && obj.status == 200){
			return true;
		}
		return false;
	};
	/**
	 * Show Hide proceesing image for every Ajax call
	 */
	this.ShowHideProcessing = function(){
		if(document.getElementById('processingImage').style.display == 'none')
			{
			document.getElementById('processingImage').style.display='block';
		}else{
			document.getElementById('processingImage').style.display = 'none';
		}
	}
	/**
	 * Bind jquery calender to TextBox class = datePickerTextBox (Date)
	 */
	this.bindDatePicker = function () {
		$(".datePickerTextBox").datepicker({
			dateFormat : 'mm/dd/y',
			minDate: 0,
			maxDate: 60,
		});
	};
	/**
	 * Bind jquery calender to TextBox class = datePickerTextBox (Date)
	 */
	this.bindDate2Picker = function () {
		$(".datePickerTextBox").datepicker({
			changeMonth: true,
			changeYear: true,
			dateFormat : 'yy-mm-dd',
			maxDate: 0,
		});
	};
	/**
	 * Bind jquery calender to TextBox class = dateTimePickerTextBox (DateTime)
	 */
	this.bindDateTimePicker= function () {
		$(".dateTimePickerTextBox").datetimepicker({
			ampm: true,
			dateFormat : 'mm/dd/y',
			timeFormat : 'hh:mm TT',
			stepMinute: 15,
			hourGrid: 4,
			minuteGrid: 15,
			separator : '@',
			minDate: 0,
		    maxDate: 60,
		});
	};
	/**
	 * Javascript RegularExpression for Trim
	 */
	this.trim = function(stringVal) {
		return stringVal.replace(/^\s+|\s+$/g,"");
	}

	/**
	 * Custom replace for more than 5 store count match in the string
	 */
	this.customReplaceStoreCount = function (strData, strTextToReplace, strReplaceWith, replaceAt) {
		
		var tempStrData = strData;
		
		if(strData.split(strTextToReplace).length > replaceAt){
			var index = strData.indexOf(strTextToReplace);
		    for (var i = 1; i < replaceAt; i++)
		        index = strData.indexOf(strTextToReplace, index + 1);
		    if (index >= 0)
		    	
		    	tempStrData = common.insertNthChar(tempStrData,'<br>',7);
		    
		        return strData.substr(0, index) + strReplaceWith 
		        		+ "  <div style='display:inline-block;'>[<font style='FONT-WEIGHT: bold'>"+strData.split(strTextToReplace).length+" Store(s)</font>] "
		        		+"<img items='"+tempStrData+"' style='width:10px;height:10px;cursor:pointer;' src='images/tooltips.jpg' class='imgToolTipsCls'/></div>";
		}    
	    return strData;
	};
	
	this.insertNthChar = function(string,chr,nth) {
  	  var output = '';
  	  var arrString = string.split(',');
	  for (var i=0; i<arrString.length; i++) {
		  if(output!='') output +=',';
		  if (i>0 && i%nth == 0)
			  output += chr;
		  output += arrString[i];
	  }
  	  
  	  return output;
  	};
	
	/**
	 * Custom replace for more than 5 store count match in the string
	 */
	this.customStringSizeLimit = function (strData, requiredStringSize, strReplaceWith) {
		if(strData.length > requiredStringSize){
			return strData.substr(0,requiredStringSize) + strReplaceWith;
		}else return strData;
	};
	
	/**
	 * Clear Textbox
	 */
	this.clearTextBox = function(txtId){
		var obj = document.getElementById(txtId);
		if(commonValidation.NullValidate(obj)){
			obj.value = "";
		}
	};
	/**
	 * Clear Textbox based on default date format
	 */
	this.clearInput = function (dateTxtBox) {
		if (dateTxtBox.value==defaultDateFormat) dateTxtBox.value="";
	}
	/**
	 * Restore default Date Format in Date Textbox
	 */
	this.restoreInput = function (dateTxtBox) {
		if (commonValidation.isEmpty(dateTxtBox)) dateTxtBox.value=defaultDateFormat;
	}
	/**
	 * cast  stringToBoolean
	 */
	this.stringToBoolean = function (str) {
		var val = false;
		if (str!= null && (str.toLowerCase()=='y' || 
				str.toLowerCase()=="YES" || 
				str.toLowerCase()=="1"||
				str.toLowerCase()=="true")) {
			val = true;
		}
		return val;
	};
	/**
	 * Select item from list of items in drop down
	 */
	this.selectItemByValue = function (elmnt, text){
		
	    for(var i=0; i < elmnt.options.length; i++)
	    {
	      if(elmnt.options[i].text == text) {
	    	  elmnt.selectedIndex = i;
	      }	     
	    }
	 };
	 
	 this.intializeOptionsSelected = function(elmnt, booleanVal){
		if(elmnt.options){
		    for(var i=0; i < elmnt.options.length; i++)
		    {
		    	elmnt.options[i].selected=booleanVal;
		    }
		}
	 };
	 
	/**
	 * Select item from list of items in drop down
	 */
	this.newSelectItemByValue = function (elmnt, text){
		
	    for(var i=0; i < elmnt.options.length; i++)
	    {
	      if(elmnt.options[i].text == text) {
	    	  //common.setElementAttribute(elmnt.options[i], "selected", "selected")
	    	  elmnt.options[i].selected=true;
	      }	     
	    }
	 };
	 
	 /**
	  * Create dynamic input  type="text" Element 
	  */
	this.createTextBox = function (containerElementObj, value){
		var objInput = document.createElement("input");
 		objInput.type = "text";
 		objInput.value = value;
 		containerElementObj.appendChild(objInput);
	};
	
	
	/**
	 * Create dynamic input type="hidden" Element 
	 */
	this.createHiddenTextBox = function (containerElementObj, value, id) {
		var objInput = document.createElement("input");
		objInput.type = "hidden";
		objInput.value = value;
		objInput.id = id;
		containerElementObj.appendChild(objInput);
	}
	
	 /**
	  * Create dynamic input  type="file" Element 
	  */
	this.createFileUpload = function (containerElementObj, idAppender, value){
		var objInputFile = document.createElement("input");
    	objInputFile.type = "file";
    	objInputFile.id = "fileUpload"+idAppender;
    	objInputFile.name = "fileUpload"+idAppender; // DONOT remove name & id attribute (Compulsary for file upload)
    	objInputFile.style.width = "1px";
    	objInputFile.style.margin = "6px";
    	containerElementObj.appendChild(objInputFile);
    	
    	var objInputBtn = document.createElement("input");
    	objInputBtn.type = "button";
    	objInputBtn.id = "btnFileUpload"+idAppender;
    	objInputBtn.style.margin = "-8px";
    	objInputBtn.value = value
    
		containerElementObj.appendChild(objInputBtn);
	};

	 /**
	  * Create alert  
	  */
	this.createAlertImg = function (title){
		var divObj = document.createElement("div");
		divObj.title = title;
		common.setElementAttribute(divObj,'class','clsAlert');
		divObj.innerHTML = '?';
		//divObj.innerHTML = '<img src="images/icontexto-message-types-alert-red.png"/>';
 		
 		return divObj;
	};
	
	this.setTDColorAttribute = function (containerElementObj , rowCount, className, classNameAlt){
		if((rowCount%2)==0){
			common.setElementAttribute(containerElementObj,'class',classNameAlt);	
		}else common.setElementAttribute(containerElementObj,'class',className);
	};
	
	this.setElementAttribute = function (containerElementObj, AttributeName, AttributeValue){
		containerElementObj.setAttribute(AttributeName, AttributeValue);
	};	
	/** 
	common functionality for filling the drop-down (Combo-box).
	Parameter required are : Combo-box ID , Values , Flag to say whether to add --Please select -- field in the combo box.
	*/
	this.loadDropDownValues = function(comboBoxObj, mapComboBoxValues,addSelectOption){
		
		// validating the combo box object
		if(commonValidation.NullValidate(comboBoxObj)){
			/// validating the combo box value
			if(addSelectOption){
				comboBoxObj.add(new Option("Please Select","Please Select"),0);
			} 
			if(commonValidation.NullValidate(mapComboBoxValues)){		
				for (var key in mapComboBoxValues) {
					var value = mapComboBoxValues[key];
		  			if(commonValidation.NullValidate(value)){
		  				comboBoxObj.add(new Option(key,value));
		  			}
				}
			}
		}
	};
	
	this.createAndLoadDropDownValues = function(containerElementObj, addSelectOption, mapComboBoxValues, allGeoOptions){
		var comboBoxObj = document.createElement("select");
		
		// validating the combo box object
		if(commonValidation.NullValidate(comboBoxObj)){
			/// validating the combo box value
			if(addSelectOption){
				comboBoxObj.add(new Option("Please Select","Please Select"),0);
			}else{
				if(allGeoOptions){
					comboBoxObj.add(new Option("All Geos","All Geos"),0);
				}
			} 
			if(commonValidation.NullValidate(mapComboBoxValues)){		
				for (var key in mapComboBoxValues) {
					var value = mapComboBoxValues[key];
		  			if(commonValidation.NullValidate(value)){
		  				comboBoxObj.add(new Option(key,value));
		  			}
				}
			}
		}
 		containerElementObj.appendChild(comboBoxObj);
	};
	
	this.createAndLoadCheckBox = function(containerElementObj, value , text, flag, name){
  		var objChkbox = document.createElement('input');
  		objChkbox.type = "checkbox";
  		objChkbox.value = value; 
  		objChkbox.name = name;
  		objChkbox.checked = flag;
  		var objDiv = document.createElement('div');
  		common.setElementAttribute(objDiv,'class','clsDivTab');	 //Div for checkbox+label
  		objDiv.appendChild(objChkbox);
  		
  		if(commonValidation.NullValidate(text)){
  			var label = document.createTextNode(text+'\u00A0');//Label + Add space after each element \u00A0
  			objDiv.appendChild(label); 
  		}
  		containerElementObj.appendChild(objDiv); 	          			     
	};
	
	this.createAndLoadComponentCheckBox = function(containerElementObj, value , text, flag, name){
  		var objChkbox = document.createElement('input');
  		objChkbox.type = "checkbox";
  		objChkbox.value = value; 
  		objChkbox.name = name;
  		objChkbox.checked = flag;
  		var objDiv = document.createElement('div');
  		common.setElementAttribute(objDiv,'class','clsDivTab');	 //Div for checkbox+label
  		common.setElementAttribute(objChkbox,'disabled','true');
  		objDiv.appendChild(objChkbox);
  		
  		if(commonValidation.NullValidate(text)){
  			var label = document.createTextNode(text+'\u00A0');//Label + Add space after each element \u00A0
  			objDiv.appendChild(label); 
  		}
  		containerElementObj.appendChild(objDiv); 	          			     
	};
	
	this.createAndLoadRadioBtnList = function (containerElementObj, rdoBtnNameAppender, valueArray){
		var cell = containerElementObj;
		for(var key in valueArray){
			var objRdo = document.createElement('input');
	 		objRdo.type = "radio";
	 		objRdo.name = "rdo"+rdoBtnNameAppender;
	 		objRdo.value = valueArray[key];
	 		var label = document.createTextNode(objRdo.value+'\u00A0');//Label + Add space after each element \u00A0
			var objDiv = document.createElement('div');
			common.setElementAttribute(objDiv,'class','clsDivTab');
			objDiv.appendChild(objRdo);
			objDiv.appendChild(label);
			cell.appendChild(objDiv);
		}
		
	};
	/**
	 * Check for CheckBox true/false 
	 */
	this.isCheckedTF = function (table){
        var rowCount = table.rows.length;
        for(var k=1; k<rowCount; k++) {
    		var row = table.rows[k];
    		var chkbox = row.cells[0].childNodes[0].childNodes[0];
        	if(commonValidation.NullValidate(chkbox) && true == chkbox.checked) {
        		return true;
        	}
        }
       return false;
	};
	/**
	 * To check/un-check all rows
	 */
	this.checkAll = function(allChkId, tableId) {
		var allChkObj = document.getElementById(allChkId);
     	var table = document.getElementById(tableId);
     	var rowCount = table.rows.length;
     	
     	if(commonValidation.NullValidate(allChkObj) && true == allChkObj.checked) {
     		for(var i=1; i<rowCount; i++) {
	            var row = table.rows[i];
	            var chkbox = row.cells[0].childNodes[0].childNodes[0];
	            if(commonValidation.NullValidate(chkbox) && false == chkbox.checked) {
	            	chkbox.checked = true;
	            }
     		}
     	}else{
			 for(var i=1; i<rowCount; i++) {
		            var row = table.rows[i];
		            var chkbox = row.cells[0].childNodes[0].childNodes[0];
		            if(commonValidation.NullValidate(chkbox) && true == chkbox.checked) {
		            	chkbox.checked = false;
		            }
			 }
		 }
	};
	
	//delete one or more row from table
	this.deleteRowConfirm = function(tableId){
		var table = document.getElementById(tableId);
        var rowCount = table.rows.length;
        if (rowCount ==1){
        	common.showMessage("Record(s) not found to be deleted!!");
        }else {
        	if(common.isCheckedTF(table)){
        		if (false != confirm("Do you want to delete selected record(s)?")){
        			for(var i=1; i<rowCount; i++) {
                		var row = table.rows[i];
                		var chkbox = row.cells[0].childNodes[0].childNodes[0];
                    	if(commonValidation.NullValidate(chkbox) && true == chkbox.checked) {
                    		table.deleteRow(i);
                       	 	rowCount--;
                       	 	i--;
                    	}
                	}
        		}
        	}else {
        		common.showMessage("Please check record(s) to be deleted!!");
        	}
        }
	};
	
	this.alignTableAlternateColor = function (tableId, numCheckPoint){
		 var table = document.getElementById(tableId);
	     var rowCount = table.rows.length;
	     if (rowCount > numCheckPoint){
	    	 for(var i=numCheckPoint; i<rowCount; i++) {
	    		var row = table.rows[i];	    		
	    			common.setTDColorAttribute(row, i, 'clsCommonTDBGAltColor','clsCommonTDBGColor');
	    	 }
	     }
	};
	
	this.showHideAlertImg = function (txtBoxObj, title,flag){
		var which_TDObj = txtBoxObj.parentNode; // TextBox --> <td>
		var divAlertImg = which_TDObj.childNodes[1];
		if(flag){
			divAlertImg.style.display = "inline-block";
			common.setElementAttribute(divAlertImg,'title',title);
			divAlertImg.onclick = function () {
				common.showMessage(title);
			}
		}else {
			divAlertImg.style.display = "none";
		}
	};
	
	this.removeDelimeter = function (string, delimiter) {
		var arryString = common.trim(string).split(delimiter);
		if(arryString[arryString.length-1] == ""){
			arryString.splice(arryString.length-1, arryString.length);
		}
		return arryString.toString();
	};
	
	this.loadAndShowPopupMsgWindow = function (displayFlag, message, popupId){
		
		if(displayFlag){
			$("#spnResponseMsg").html(message); //write message to show
			common.showHidePopup(popupId,displayFlag);
		}else {
			$("#spnResponseMsg").html(message); //write message to show
			centerPopup(popupId); //refer to jqueryPopupWindow.js 
		}
	};
	
	this.loadAndShowPopupContentWindow = function (popupFlag, popupId){
		
		if(popupStatus==1){  //refer "popupStatus" to jqueryPopupWindow.js //0 means disabled; 1 means enabled; 
			$("#popupProcessBar").fadeOut("slow");	
		}
			
		if(popupFlag){		
			centerPopup(popupId); //refer to jqueryPopupWindow.js 
			$("#"+popupId).fadeIn("slow"); 
			
		}else {
			common.showHidePopup(popupId,true);
		}	
	};
	
	this.showHidePopup = function(popupId,showHideflag){
		if(showHideflag){
			//centering with css  
			centerPopup(popupId); //refer to jqueryPopupWindow.js 
			//load processing popup  
			loadPopup(popupId); //refer to jqueryPopupWindow.js 
			//load store status
		}else disablePopup(popupId); //refer to jqueryPopupWindow.js 
	};
	
	this.isValidStoreId = function(storeId){
		var flag = true;
		if(!storeId.match(/[RrTt]\d{3}/) || !(storeId.length==4)){
			flag = false;	
		}
		return flag;
	};
	
	this.isValidGroupId = function(eptGrpId){
		var flag = true;
	
		if(!eptGrpId.match(/^\d+$/))
			flag = false;
		
		return flag;
	};
	
	this.isNum = function(e) {
	    var key = e.keyCode ? e.keyCode : e.which;
	    if ( isNaN( String.fromCharCode(key) ) ) return false;
	};	
	
	this.validateStoreIds = function(storeIds){
		var flag = true;
		storeIds = storeIds.replace(/\s/g, ''); // remove the space and \n
		if(!storeIds || common.trim(storeIds)==""){
			common.showMessage("divMessage","Please select/enter Store Id(s)");
			return false;
		}
		else{
			var storeId;
			if(storeIds.indexOf(',')>-1){
				storeId = storeIds.split(",");
			}else{
				storeId = [storeIds];
			}
			for(var i=0;i<storeId.length;i++){
				if(!common.isValidStoreId(storeId[i])){
					common.showMessage("divMessage","Invalid Store Id(s) found: "+storeId[i]);
					 flag = false;
					 break;
				}
			}
		}
		return flag;
	};
	
	this.validatePersonIds = function(personIds){
		var flag = true;
		personIds = personIds.replace(/\s/g, '');  // remove the space and \n
		if(!personIds || common.trim(personIds)==""){
			common.showMessage("divMessage","Please enter Person Id(s)");
			return false;
		}
		else{
			var personId;
			if(personIds.indexOf(',')>-1){
				personId = personIds.split(",");
			}else{
				personId = [personIds];
			}
			for(var i=0;i<personId.length;i++){
				if (!personId[i].match(/^\d+$/)){
					common.showMessage("divMessage","Invalid Perons Id(s) found: "+personId[i]);
					 flag = false;
					 break;
				}
			}
		}
		return flag;
	};
	
	this.validateStoreIdsOrPersonId = function(storeIdsOrPersonIds){
		var flag = true;
		storeIdsOrPersonIds = storeIdsOrPersonIds.replace(/\s/g, '');
		if(!storeIdsOrPersonIds || common.trim(storeIdsOrPersonIds)==""){
			common.showMessage("divMessage","Please enter Person Id(s)/Store Id(s)");
			return false;
		}else{
			var storeIdsOrPersonId;
			if(storeIdsOrPersonIds.indexOf(',')>-1){
				storeIdsOrPersonId = storeIdsOrPersonIds.split(",");
			}else{
				storeIdsOrPersonId = [storeIdsOrPersonIds];
			}
			for(var i=0;i<storeIdsOrPersonId.length;i++){
				if (!storeIdsOrPersonId[i].match(/^\d+$/) && !common.isValidStoreId(storeIdsOrPersonId[i])){
					common.showMessage("divMessage","Invalid Person Id(s)/Store Id(s) found: "+storeIdsOrPersonId[i]);
					 flag = false;
					 break;
				}
			}
		}
		return flag;
	};
	
	this.isNumber=function(evt) {
	    evt = (evt) ? evt : window.event;
	    var charCode = (evt.which) ? evt.which : evt.keyCode;
	    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
	        return false;
	    }
	    return true;
	}
	
};
